const api = require('../../../ws_micro_shop/utils/api.js');
const F2 = require('../../components/f2-canvas/lib/f2');
const app = getApp();

Page({
  data: {
    theme: app.themeData,
    height: wx.systemInfo.windowHeight,
    unit: '',
    abnorData: {
      imgSrc: app.imgUrl + 'abnor-15.png',
      text: '',
    },
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    status: 'day',
    date: '',
    checked: 0,
    selected: 0,
    isSortSale: false,
    isSortMember: false,
    _switch: true,
    showNum: 5,
    sort: -1,
    page: 2,
    orderby: 'down',
    achieveList: [],
    imageUrl0: '/ws_micro_shop_guide/common/images/paixu.png',
    imageUrl1: '/ws_micro_shop_guide/common/images/paixu2.png',
    imageUrl2: '/ws_micro_shop_guide/common/images/paixu1.png',
    checkedSale: 0,
    checkedMember: 0,
    salesList: [
      { name: '销售明细' },
      { name: '新会员' },
    ],
    isChangeColor: true,
    singleList: [],
    showList: [],
    is_show_line: false,
    isHidden: false,
    isShow: false,
    imgUrl: app.imgUrl,
  },
  onLoad(opts) {
    let options = opts || {};
    let title = Number(options.is_guide) === -1 ? '平台业绩' : (Number(options.is_guide) === 0 ? '本店业绩' : '我的业绩');
    wx.setNavigationBarTitle({
      title: title,
    });
    let corpid = wx.getStorageSync('corpid');

    this.setData({
      is_guide: options.is_guide || app.ws_micro_shop_globalData.role,
      ...options,
      endDate: this.addDate(0),
      sameDate: this.addDate(1),
      isHidden: false,
      isSaas: app.ws_micro_shop_globalData.isSaas,
      corpid
    })
  },
  onShow() {
    let { is_guide } = this.data;
    this.changeAbnorText();
    this.loadList();
    this.loadInit(is_guide);
  },
  loadInit(is_guide) {
    Number(is_guide) === -1 && this.anotherload();
    Number(is_guide) === 1 && this.getList();
  },
  changeAbnorText() {
    let text = '';
    if (Number(this.data.selected) === 1) {
      text = '暂无新会员';
    } else {
      text = '暂无销售明细';
    }
    this.setData({
      'abnorData.text': text,
    });
  },
  initAreaChartComponent(list) {
    this.areaChartComponent = this.selectComponent('#area-dom');
    // list = list.sort((a, b) => a.value - b.value);
    this.areaChartComponent.init((canvas, width, height) => {
      let data = list;
      const chart = new F2.Chart({
        el: canvas,
        width,
        height,
      });

      chart.source(data, {
        axis: {
          tickCount: 8,
        },
        value: {
          min: 0,
        },
      });

      chart.axis('axis', {
        line: {
          lineWidth: 1,
          stroke: '#ccc',
          top: false, // 展示在最下层
        }, // 设置坐标轴线的样式，如果值为 null，则不显示坐标轴线，图形属性
        labelOffset: 20, // 坐标轴文本距离轴线的距离
      });
      // chart.axis('value', false);

      chart.tooltip({
        showCrosshairs: true,
        layout: 'vertical',
        showItemMarker: true,
        crosshairsStyle: {
          stroke: '#707070',
          lineWidth: 2,
        }, // 配置辅助线的样式
        offsetX: 0, // x 方向的偏移
        offsetY: 30, // y 方向的偏移
        background: {
          radius: 2,
          fill: '#000',
          padding: [9, 10],
        },
        nameStyle: {
          fontSize: 10,
          fill: '#fff',
          textAlign: 'start',
          textBaseline: 'middle',
        },
        onShow(ev) {
          const items = ev.items;
          items[0].name = items[0].origin.type;
        },
      });

      chart.legend({
        marker: 'circle',
        align: 'left',
        marker: {
          symbol: 'square', // marker 的形状
          radius: 5, // 半径大小
        },
        nameStyle: {
          fill: '#999999', // 文本的颜色
          fontSize: '12', // 文本大小
          height: 17, // 设置文本的高度
        },
        itemWidth: null, // 图例项按照实际宽度渲染
      });

      chart.line().position('axis*value').color('type', function (val) {
        if (val === '目标销售额') {
          return '#D9E7FD';
        } else if (val === '实际销售额' || val === '销售额') {
          return '#4185F4';
        } else if (val === '目标拉新数') {
          return '#FFEACC';
        } else if (val === '实际拉新数' || val === '拉新会员') {
          return '#FF9500';
        }
      });
      // chart.point()
      //   .position('month*value')
      //   .style({
      //     lineWidth: 1,
      //     stroke: '#fff'
      //   });

      chart.render();
      // return chart;
      // 默认展示 tooltip
      let item = JSON.parse(JSON.stringify(data[data.length - 1])); // 要展示 tooltip 的数据
      Number(this.data.status) === 1 && (item.axis = (new Date(this.data.date).getMonth() + 1) + '月');
      delete item.value;
      let point = chart.getPosition(item); // 获取该数据的画布坐标
      chart.showTooltip(point); // 展示该点的 tooltip
    });
  },
  addDate(num) {//获取当前月的前一个月
    let date = new Date();
    let month = date.getMonth();
    if (num === 0) {
      if(month===0){
        return (date.getFullYear()-1) + '-' + 12;
      }else{
        return date.getFullYear() + '-' + this.getFormatDate(month);
      }
    } else {
      return date.getFullYear() + '-' + this.getFormatDate(month + 1);
    }
    
  },
  // 日期月份/天的显示，如果是1位数，则在前面加上'0'
  getFormatDate(arg) {
    if (!arg) {
      return '';
    }
    let re = String(arg);
    if (re.length < 2) {
      re = '0' + re;
    }
    return re;
  },
  bindDateChange(e) {
    let dataset = e.currentTarget.dataset;
    let { is_guide } = this.data;
    this.setData({
      date: e.detail.value,
      isChangeColor: false,
      status: dataset.status
    });
    Number(dataset.status) === 1 && this.loadList();
    this.loadInit(is_guide);
  },
  bindcancel(e) {
    // if (this.data.lastStatus != 1) {
      this.setData({
        // status: this.data.lastStatus,
        isChangeColor: true,
      });
    // }
  },
  switchList(e) {
    let dataset = e.currentTarget.dataset;
    let isChangeColor;
    if (dataset.status !== 1) isChangeColor = true;
    this.setData({
      lastStatus: this.data.status,
      status: dataset.status,
      date: dataset.status !== 1 ? '' : this.data.date,
      isChangeColor: isChangeColor,
      isSortSale: false,
      isSortMember: false,
      checkedMember:0,
      checkedSale:0,
      checked: 0,
      selected: 0,
      switchList: true,
      imageList: [
        {
          name: '销售额',
          checked: false,
        },
        {
          name: '新会员',
          checked: false,
        },
      ],
      is_show_line: false,
    });

    dataset.status != 1 && this.loadList();
    this.loadInit(this.data.is_guide);
    this.changeAbnorText();
  },
  checkList(e) {
    let { list } = this.data;
    let dataset = e.currentTarget.dataset;
    let chartslist;
    this.setData({
      ...dataset,
      page: 2,
      is_show_line: false,
      isHidden: true,
      checked: dataset.selected,
      selected: dataset.selected,
    });
    chartslist = Number(this.data.checked) === 0 ? list.order_charts : list.user_charts;
    this.initAreaChartComponent(chartslist);
    this.changeAbnorText();
    this.getList();
  },
  switchchecked(e) {
    let { list, is_guide} = this.data;
    let dataset = e.currentTarget.dataset;
    let chartslist;
    this.setData({
      checked: dataset.checked,
      selected: dataset.checked,
    });
    chartslist = Number(this.data.checked) === 0 ? list.order_charts : list.user_charts;
    this.initAreaChartComponent(chartslist);
    this.changeAbnorText();
    Number(is_guide) === 1 && this.getList();
  },
  paixuClick(e) {
    let { sort } = e.currentTarget.dataset;
    let { checkedMember, checkedSale, isSortSale, isSortMember } = this.data;
    let checkStatus = 0;
    if (Number(sort) === 0) {
      let ifSort = !isSortSale;
      if (Number(checkedSale) === 1) {
        checkStatus = 2;
      } else {
        checkStatus = 1;
      }
      this.setData({
        checkedSale: checkStatus,
        checkedMember: 0,
        sort: sort,
        isSortSale: ifSort,
        orderby: ifSort ? 'up' : 'down',
        isSortMember: false,
      });
    } else {
      let ifSort = !isSortMember;
      if (Number(checkedMember) === 1) {
        checkStatus = 2;
      } else {
        checkStatus = 1;
      }
      this.setData({
        checkedMember: checkStatus,
        checkedSale: 0,
        sort: sort,
        isSortMember: ifSort,
        orderby: ifSort ? 'up' : 'down',
        isSortSale: false,
      });
    }
    this.anotherload();
  },

  anotherload() {
    let _this = this;
    let { status, date, sort, orderby } = _this.data;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.performance_index_shop,
      data: {
        type: Number(status) === 1 ? date : status,
        status: sort,
        orderby,
      },
      success: function (res) {
        if (res.code === 0) {
          _this.setData({
            saleList: res.data.shop_performance_top || [],
          });
        }
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  loadList() {
    let _this = this;
    let { status, sameDate = '', date = '', is_guide, role} = _this.data;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.achieve,
      data: {
        type: status === 'day' ? 0 : 1,
        date: Number(status) === 1 ? date : (status === 'day' ? '' : sameDate),
        is_my: Number(is_guide) === 1 && Number(role) === 0 ? 1 : 0
      },
      success: function (res) {
        if (res.code === 0) {
          _this.setData({
            list: res.data,
            achieveList: res.data.guide_info || [],
            isShow: true,
          });
          _this.initAreaChartComponent(res.data.order_charts || []);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      },
      complete: function() {
        wx.hideLoading();
      }
    });
  },
  getList() {
    let { status, date, selected } = this.data;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.target_detail,
      data: {
        type: Number(status) === 1 ? date : status,
        status: Number(selected) + 1,
        page: 1,
      },
      success: res => {
        if (res.code === 0) {
          let list = res.data;
          this.setData({
            showList: list,
            isHidden: false,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: ()=> {
        wx.hideLoading();
      }
    });
  },
  onReachBottom() {
    this.loadmore();
  },
  loadmore() {
    let that = this;
    let { status, date, selected, showList, page } = that.data;
    let oldlist = showList;
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.target_detail,
      data: {
        type: status === 1 ? date : status,
        status: selected + 1,
        page: page,
      },
      success: function (res) {
        if (res.code === 0) {
          let list = res.data;
          let newlist = [];
          if (list.length > 0) {
            newlist = oldlist.concat(list);
            page += 1;
          } else {
            newlist = oldlist;
            that.setData({
              is_show_line: page > 1 ? true : false,
            });
          }
          that.setData({
            showList: newlist,
            page: page,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      },
      complete: function () {
        wx.hideLoading();
      },
    });
  },
  onNavigate(e) {
    let param = e.currentTarget.dataset;
    app.ws_micro_shop_navigate(param);
  },
  collectFormId(e) {
    app.collectFormId(e);
  },
  getMore() {
    this.setData({
      showNum: 10000,
    });
  },
});
